package org.computate.tool;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Date;

import org.apache.tools.ant.util.DateUtils;
import org.computate.form.ComputateForm;
import org.computate.model.item.Model;

public class FormTool {

	public static Object getValue(ComputateForm computateForm, String fieldName) {
		Object result = null;
		
		if(computateForm != null) {
			try {
				Method getter = new PropertyDescriptor(fieldName, computateForm.getClass()).getReadMethod();
				
				result = getter.invoke(computateForm);
			} catch (SecurityException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IntrospectionException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		return result;
	}
	
	public static String getValueString(ComputateForm computateForm, String fieldName) {
		String resultString = null;
		Object resultObject = getValue(computateForm, fieldName);
		
		if(resultObject != null) {
			if(resultObject instanceof String) {
				resultString = (String)resultObject;
			}
			else if(resultObject instanceof Date) {
				Date result = (Date)resultObject;
				resultString = DateUtils.format(result, "EEE MMM d, yyyy");
			}
			else if(resultObject instanceof Boolean) {
				Boolean result = (Boolean)resultObject;
				
				if(result)
					resultString = "yes";
				else
					resultString = "no";
			}
			else if(resultObject instanceof Integer) {
				Integer result = (Integer)resultObject;
				resultString = result.toString();
			}
			else if(resultObject instanceof Model) {
				Model result = (Model)resultObject;
				resultString = result.getName();
			}
		}
		
		return resultString;
	}
}
